<?php

/**
 * @file classes/journal/DMKHODAO.inc.php
 *
 * Copyright (c) 2003-2012 John Willinsky
 * Distributed under the GNU GPL v2. For full terms see the file docs/COPYING.
 *
 * @class DMKHODAO
 * @ingroup journal
 * @see DMKHO
 *
 * @brief Operations for retrieving and modifying DMKHO objects.
 */

// $Id$

define('DMKHO_FIELD_MAKHO', 'MAKHO');
define('DMKHO_FIELD_TENKHO', 'TENKHO');
define('DMKHO_FIELD_NONE', null);



import ('classes.acct.DMKHO');

class DMKHODAO extends DAO {
	var $cache;

	function _cacheMiss(&$cache, $id) {
		$DMKHO =& $this->getDMKHO($id, null, false);
		$cache->setCache($id, $DMKHO);
		return $DMKHO;
	}

	function &_getCache() {
		if (!isset($this->cache)) {
			$cacheManager =& CacheManager::getManager();
			$this->cache =& $cacheManager->getObjectCache('DMKHO', 0, array(&$this, '_cacheMiss'));
		}
		return $this->cache;
	}


 	function &getDMKHO($MAKHO, $DaoFac = false, $combo = false) {
		if (isset($MAKHO))
			$result =& $this->retrieve(
				'SELECT * FROM DMKHO WHERE MAKHO = ? ORDER BY MAKHO', $MAKHO
			);
		else
			$result =& $this->retrieve(
				"SELECT * FROM DMKHO WHERE MAKHO !='' ORDER BY MAKHO");

		$sectionsIterator = new DAOResultFactory($result, $this, '_returnDMKHOFromRow');

		if ($DaoFac)
			return $sectionsIterator;
		else if (!$combo)
		{
			$returner = null;
			if ($result->RecordCouKHO() != 0) {
				$returner =& $this->_returnDMKHOFromRow($result->GetRowAssoc(false));
			}

			$result->Close();
			unset($result);
			return $returner;
		}


		$sections = $returner ;

		while (($section =& $sectionsIterator->next())) {
			$sections[$section->getMAKHO()] = $section->getMAKHO()."-".$section->gettenKHO();
			unset($section);
		}
		return $sections;
	}


 	function &getDSKHO($MAKHO) {
		if (isset($MAKHO))
			$result =& $this->retrieve(
				'SELECT * FROM DMKHO WHERE MAKHO = ? ORDER BY MAKHO', $MAKHO
			);
		else
			$result =& $this->retrieve(
				"SELECT * FROM DMKHO WHERE MAKHO !='' ORDER BY MAKHO");

		$sectionsIterator = new DAOResultFactory($result, $this, '_returnDMKHOFromRow');

		$sections = $returner ;

		while (($section =& $sectionsIterator->next())) {
			$sections[trim($section->getmakho())] = trim($section->getmakho())."-".trim($section->gettenkho());
			unset($section);
		}
		//var_dump($sections);
		return $sections;
	}
	


 	function &getDSMAKHO_MA($MAKHO) {
		if (isset($MAKHO))
			$result =& $this->retrieve(
				'SELECT * FROM DMKHO WHERE MAKHO = ? ORDER BY MAKHO', $MAKHO
			);
		else
			$result =& $this->retrieve(
				"SELECT * FROM DMKHO WHERE MAKHO !='' ORDER BY MAKHO");

		$sectionsIterator = new DAOResultFactory($result, $this, '_returnDMKHOFromRow');

		$sections = $returner ;

		while (($section =& $sectionsIterator->next())) {
			$sections[$section->getmant()] = $section->getmant();
			unset($section);
		}
		//var_dump($sections);
		return $sections;
	}


	function &_returnDMKHOFromRow(&$row) {
		$DMKHO = new DMKHO($row['makho'], $row['tenkho']);
		return $DMKHO;
	}


	function &getDMKHOSearch($searchType = null, $search = null, $searchMatch = null) {

		$paramArray = array();
		$searchSql = '';

		$searchTypeMap = array(
			DMKHO_FIELD_MAKHO => 'DMKHO.mant',
			DMKHO_FIELD_TENKHO => 'DMKHO.tennt'

		);

		if (!empty($search) && isset($searchTypeMap[$searchType])) {

			$fieldName = $searchTypeMap[$searchType];
			switch ($searchMatch) {
				case 'is':
					$searchSql = "AND LOWER($fieldName) = LOWER(?)";
					$paramArray[] = $search;
					break;
				case 'contains':
					$searchSql = "AND LOWER($fieldName) LIKE LOWER(?)";
					$paramArray[] = '%' . $search . '%';
					break;
				case 'startsWith':
					$searchSql = "AND LOWER($fieldName) LIKE LOWER(?)";
					$paramArray[] = $search . '%';
					break;
			}
		}
//		elseif (!empty($search)) switch ($searchType) {
//			case USER_FIELD_USERID:
//				$searchSql = 'AND u.user_id=?';
//				$paramArray[] = $search;
//				break;
//			case USER_FIELD_INITIAL:
//				$searchSql = 'AND LOWER(u.last_name) LIKE LOWER(?)';
//				$paramArray[] = $search . '%';
//				break;
//		}

		//$searchSql .= ($sortBy?(' ORDER BY ' . $this->getSortMapping($sortBy) . ' ' . $this->getDirectionMapping($sortDirection)) : '');
		$result =& $this->retrieve(
				"SELECT * FROM DMKHO WHERE MAKHO !='' ". $searchSql. " ORDER BY MAKHO",
			$paramArray
		);

		$returner = new DAOResultFactory($result, $this, '_returnDMKHOFromRow');
	
		return $returner;
	}



	function deleteTKByMa($DMKHOId) {
		return $this->update(
			'DELETE FROM DMKHO WHERE MAKHO = ? ',
			array($DMKHOId)
			);
	}






	

	function updateLocaleFields(&$DMKHO) {
		$this->updateDataObjectSettings('DMKHO_settings', $DMKHO, array(
			'DMKHO_id' => $DMKHO->getId()
		));
	}

	/**
	 * Insert a new DMKHO.
	 * @param $DMKHO DMKHO
	 */
	function insertDMKHO(&$DMKHO) {
		$this->update(
			'INSERT INTO DMNT
				(MAKHO, tennt)
				VALUES
				(?, ?)',
			array(
				$DMKHO->getMAKHO(),
				$DMKHO->gettennt()
			)
		);

		$DMKHO->setId($this->getInsertDMKHOId());
		$this->updateLocaleFields($DMKHO);
		return $DMKHO->getId();
	}

	/**
	 * Update an existing DMKHO.
	 * @param $DMKHO DMKHO
	 */
	function updateDMKHO(&$DMKHO) {
		$returner = $this->update(
			'UPDATE DMKHO
				SET
					MAKHO = ?,
					tennt = ?
				WHERE MAKHO = ?',
			array(
				$DMKHO->getMAKHO(),
				$DMKHO->gettennt(),
				$DMKHO->getMAKHO()
			)
		);
		$this->updateLocaleFields($DMKHO);
		return $returner;
	}

	/**
	 * Delete a DMKHO.
	 * @param $DMKHO DMKHO
	 */
	function deleteDMKHO(&$DMKHO) {
		return $this->deleteDMKHOById($DMKHO->getId(), $DMKHO->getJournalId());
	}

	/**
	 * Delete a DMKHO by ID.
	 * @param $DMKHOId int
	 * @param $journalId int optional
	 */

	/**
	 * Delete DMNT by journal ID
	 * NOTE: This does not delete dependent entries EXCEPT from DMNT_editors. It is intended
	 * to be called only when deleting a journal.
	 * @param $journalId int
	 */
	function deleteDMNTByJournal($journalId) {
		$DMNT =& $this->getJournalDMNT($journalId);
		while (($DMNT =& $DMNT->next())) {
			$this->deleteDMNT($DMNT);
			unset($DMNT);
		}
	}

	/**
	 * Check if a DMNT exists with the specified ID.
	 * @param $DMNTId int
	 * @param $journalId int
	 * @return boolean
	 */
	function DMNTExists($DMNTId, $journalId) {
		$result =& $this->retrieve(
			'SELECT COUNT(*) FROM DMNT WHERE DMNT_id = ? AND journal_id = ?',
			array($DMNTId, $journalId)
		);
		$returner = isset($result->fields[0]) && $result->fields[0] == 1 ? true : false;

		$result->Close();
		unset($result);

		return $returner;
	}

	/**
	 * Sequentially renumber DMNT in their sequence order.
	 * @param $journalId int
	 */
	function resequenceDMNT($journalId) {
		$result =& $this->retrieve(
			'SELECT DMNT_id FROM DMNT WHERE journal_id = ? ORDER BY seq',
			$journalId
		);

		for ($i=1; !$result->EOF; $i++) {
			list($DMNTId) = $result->fields;
			$this->update(
				'UPDATE DMNT SET seq = ? WHERE DMNT_id = ?',
				array(
					$i,
					$DMNTId
				)
			);

			$result->moveNext();
		}

		$result->close();
		unset($result);
	}

	/**
	 * Get the ID of the last inserted DMNT.
	 * @return int
	 */
	function getInsertDMNTId() {
		return $this->getInsertId('DMNT', 'DMNT_id');
	}

	/**
	 * Delete the custom ordering of an issue's DMNT.
	 * @param $issueId int
	 */
	function deleteCustomDMNTOrdering($issueId) {
		return $this->update(
			'DELETE FROM custom_DMNT_orders WHERE issue_id = ?', $issueId
		);
	}

	/**
	 * Delete a DMNT from the custom DMNT order table.
	 * @param $issueId int
	 * @param $DMNTId int
	 */
	function deleteCustomDMNT($issueId, $DMNTId) {
		$sequence = $this->getCustomDMNTOrder($issueId, $DMNTId);

		$this->update(
			'DELETE FROM custom_DMNT_orders WHERE issue_id = ? AND DMNT_id = ?', array($issueId, $DMNTId)
		);

		// Reduce the DMNT order of every successive DMNT by one
		$this->update(
			'UPDATE custom_DMNT_orders SET seq = seq - 1 WHERE issue_id = ? AND seq > ?', array($issueId, $sequence)
		);
	}

	/**
	 * Sequentially renumber custom DMNT orderings in their sequence order.
	 * @param $issueId int
	 */
	function resequenceCustomDMNTOrders($issueId) {
		$result =& $this->retrieve(
			'SELECT DMNT_id FROM custom_DMNT_orders WHERE issue_id = ? ORDER BY seq',
			$issueId
		);

		for ($i=1; !$result->EOF; $i++) {
			list($DMNTId) = $result->fields;
			$this->update(
				'UPDATE custom_DMNT_orders SET seq = ? WHERE DMNT_id = ? AND issue_id = ?',
				array($i, $DMNTId, $issueId)
			);

			$result->moveNext();
		}

		$result->close();
		unset($result);
	}

	/**
	 * Check if an issue has custom DMNT ordering.
	 * @param $issueId int
	 * @return boolean
	 */
	function customDMNTOrderingExists($issueId) {
		$result =& $this->retrieve(
			'SELECT COUNT(*) FROM custom_DMNT_orders WHERE issue_id = ?',
			$issueId
		);
		$returner = isset($result->fields[0]) && $result->fields[0] == 0 ? false : true;

		$result->Close();
		unset($result);

		return $returner;
	}

	/**
	 * Get the custom DMNT order of a DMNT.
	 * @param $issueId int
	 * @param $DMNTId int
	 * @return int
	 */
	function getCustomDMNTOrder($issueId, $DMNTId) {
		$result =& $this->retrieve(
			'SELECT seq FROM custom_DMNT_orders WHERE issue_id = ? AND DMNT_id = ?',
			array($issueId, $DMNTId)
		);

		$returner = null;
		if (!$result->EOF) {
			list($returner) = $result->fields;
		}
		$result->Close();
		unset($result);

		return $returner;
	}

	/**
	 * Import the current DMNT orders into the specified issue as custom
	 * issue orderings.
	 * @param $issueId int
	 */
	function setDefaultCustomDMNTOrders($issueId) {
		$result =& $this->retrieve(
			'SELECT s.DMNT_id FROM DMNT s, issues i WHERE i.journal_id = s.journal_id AND i.issue_id = ? ORDER BY seq',
			$issueId
		);

		for ($i=1; !$result->EOF; $i++) {
			list($DMNTId) = $result->fields;
			$this->insertCustomDMNTOrder($issueId, $DMNTId, $i);
			$result->moveNext();
		}

		$result->close();
		unset($result);
	}

	/**
	 * INTERNAL USE ONLY: Insert a custom DMNT ordering
	 * @param $issueId int
	 * @param $DMNTId int
	 * @param $seq int
	 */
	function insertCustomDMNTOrder($issueId, $DMNTId, $seq) {
		$this->update(
			'INSERT INTO custom_DMNT_orders (DMNT_id, issue_id, seq) VALUES (?, ?, ?)',
			array(
				$DMNTId,
				$issueId,
				$seq
			)
		);
	}

	/**
	 * Move a custom issue ordering up or down, resequencing as necessary.
	 * @param $issueId int
	 * @param $DMNTId int
	 * @param $newPos int The new position (0-based) of this DMNT
	 * @param $up boolean Whether we're moving the DMNT up or down
	 */
	function moveCustomDMNTOrder($issueId, $DMNTId, $newPos, $up) {
		$this->update(
			'UPDATE custom_DMNT_orders SET seq = ? ' . ($up?'-':'+') . ' 0.5 WHERE issue_id = ? AND DMNT_id = ?',
			array($newPos, $issueId, $DMNTId)
		);
		$this->resequenceCustomDMNTOrders($issueId);
	}
}

?>
